import 'dart:convert';

import 'package:base_network/export.dart';
import 'package:flutter/widgets.dart';
import 'package:toast/toast.dart';
import '../common/common_util.dart';
import '../pages/bean/LoginBean.dart';
import '/pages/bean/ArticleBeanList.dart';
import '/pages/bean/BannerBeanList.dart';
import '/pages/bean/HomeArticleBean.dart';
import 'package:base_network/common_api_service.dart';

class AppApiService {
  AppApiService._();

  static void init(String baseUrl, {List<Interceptor>? interceptors}) {
    DioCreator.initDio(baseUrl, interceptors: interceptors);
  }

  static Future<String> _request(Future<String> call) async {
    try {
      return await call;
    } on DioError catch (dioError) {
      if (dioError.error?.toString().isNotEmpty == true) {
        Toast.show(dioError.error!.toString());
      }
      rethrow;
    } catch (e) {
      Toast.show(e.toString());
      rethrow;
    }
  }

  static Future<String> _requestGet({
    required String url,
    dynamic data,
  }) {
    return _request(CommonApiService.requestGet(url: url, data: data));
  }

  static Future<String> _requestPost({
    required String url,
    dynamic data,
  }) {
    return _request(CommonApiService.requestPost(url: url, data: data));
  }

  static Future<String> _requestDelete({
    required String url,
    dynamic data,
  }) {
    return _request(CommonApiService.requestDelete(url: url, data: data));
  }

  static Future<String> _requestPut({
    required String url,
    dynamic data,
  }) {
    return _request(CommonApiService.requestPut(url: url, data: data));
  }

  ///置顶文章
  static Future<TopArticleBeanList> requestArticleBeanList(BuildContext context) async {
    String string = await _requestGet(
      url: '/article/top/json',
    );
    return TopArticleBeanList.fromJson(json.decode(string));
  }

  ///首页文章列表
  static Future<HomeArticleBeanList> requestHomeArticle(
    BuildContext context,
    int page,
  ) async {
    String string = await _requestGet(
      url: '/article/list/$page/json',
    );
    return HomeArticleBeanList.fromJson(json.decode(string));
  }

  ///首页banner
  static Future<BannerBeanList> requestBannerBeanList(
    BuildContext context,
  ) async {
    String string = await _requestGet(
      url: '/banner/json',
    );
    return BannerBeanList.fromJson(json.decode(string));
  }

  ///登录
  static Future<LoginBean> requestLogin(
    BuildContext context,
    String username,
    String password,
  ) async {
    String string = await _requestPost(
      url: '/user/login',
      data: {
        "username": username,
        "password": password,
      },
    );
    LoginBean loginBean = LoginBean.fromJson(json.decode(string));
    CommonUtil.storeUserInfo(username, password, loginBean.data!.id!);
    return loginBean;
  }
}
